package com.xj.server;


import com.xj.openapi4j.service.*;
import com.xj.server.serviceInterface.TransfersSaleOrderInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@EnableScheduling
@Slf4j
public class ExecuteCommandServer {
    @Autowired
    StockService stockService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    PriceJustService priceJustService;
    @Autowired
    TransfersSaleOrderInterface transfersSaleOrderInterface;
    @Autowired
    DispatchService dispatchService;
   final static boolean IS_WINDOWS=System.getProperty("os.name").toLowerCase().contains("windows");

    public static boolean commandExec(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        List<String> commands = new ArrayList<>();
        if (!IS_WINDOWS){
            commands.addAll(Arrays.asList("/bin/sh", "-c"));
        } else {
            commands.addAll(Arrays.asList("cmd", "/c"));
        }
        commands.add(String.join(" ", args));
        try {
            Process exec = runtime.exec(commands.toArray(new String[0]));
            BufferedReader  reader=new BufferedReader(new InputStreamReader(exec.getInputStream()));
             String line;
             while((line=reader.readLine())!=null){
                 log.info(line);
             }
        //     exec.waitFor();
         //   int  exited = exec.exitValue();
            boolean exited = exec.waitFor(3, TimeUnit.MINUTES);
           if (exited){
               exec.destroy();
           }
            return exec.exitValue() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


  public void    executRestart()  throws Exception{
        String[]  command=   {"net","stop","ufnet" };
      Runtime runtime = Runtime.getRuntime();
      List<String> commands = new ArrayList<>();
       commands.addAll(Arrays.asList("cmd", "/c"));
       commands.add(String.join(" ", command));

       int i=0;
       while(i<5) {
           Process process = runtime.exec(commands.toArray(new String[0]));
           Thread.sleep(60000);
           PrintWriter out = new PrintWriter(process.getOutputStream());
           String cmd = "Y"; //你的cmd命令
           out.write(cmd); //输入你的命令
           out.flush(); //写到控制台
           BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
           String line;
           while ((line = reader.readLine()) != null) {
               log.info(line);
           }
           process.waitFor();
           int exited = process.exitValue();
           log.info("第{}次执行stop  ufnet ,result={}",i, exited);
            if(exited==0){
                break;
            }
            i++;
       }

        i=0;
       command[1]=  "start";
       while(i<5){
           Boolean result2=   commandExec(command);
           log.info("第{}次执行start net，result={}",i,result2);
          if(result2){
              break;
          }
           Thread.sleep(9000);
          i++;
       }
    }


  @Scheduled(cron = "0 0/2 *  * * ?")
    public void    executeTask() {
        try {
            log.info("开始同步存货档案");
            inventoryService.transIncrement();
        }catch (Exception err){
            err.printStackTrace();
            log.info("inventory trans error, error message="+err);
        }
        try {
            log.info("开始同步价格调整单");
            priceJustService.transIncrement();
        }catch (Exception err){
            err.printStackTrace();
            log.info("price just trans error, error message="+err);
        }

      try{
          log.info("开始删除弃审的预订单");
          transfersSaleOrderInterface.autoDelCancelAuditOrder();
      }catch (Exception err){
          err.printStackTrace();
          log.info("同步销售订单错误, error message="+err);
      }

      try{
          log.info("开始处理删除或驳回现销单");
          transfersSaleOrderInterface.autoDelDispatchlist();
          transfersSaleOrderInterface.autoDelSaleorder();
      }catch (Exception err){
          err.printStackTrace();
          log.info("同步销售订单错误, error message="+err);
      }
    }


    @Scheduled(cron = "0/15 * *  * * ?")
    public    void    transU8Stock(){
        try {
            log.info("开始同部U8库存变动引起的现存量");
            stockService.transIncrement();
        }catch (Exception err){
            err.printStackTrace();
            log.info("u8stock trans error, error message="+err);
        }


        try {
            log.info("开始同步销售出库引起的现存量");
            dispatchService.transStockBySaleout();
        }catch (Exception err){
            err.printStackTrace();
            log.info("stock saleout error, error message="+err);
        }
    }


    @Scheduled(cron = "0/15 * *  * * ?")
    public  void  transSaleOrder(){
        try{
            log.info("开始同步销售订单");
            transfersSaleOrderInterface.autoTransSaleOrder();
        }catch (Exception err){
            err.printStackTrace();
            log.info("同步销售订单错误, error message="+err);
        }
    }


    @Scheduled(cron = "40 41 2 * * ?")
    public void    updateAll() {
        try {
            log.info("开始同步存货档案");
            inventoryService.transInventory(3,null);
        }catch (Exception err){
            err.printStackTrace();
            log.info("inventory trans error, error message="+err);
        }

        try {
            log.info("开始同部U8库存变动引起的现存量");
            stockService.transStockAll();
        }catch (Exception err){
            err.printStackTrace();
            log.info("stock trans error, error message="+err);
        }
    }

}
